package fr.babostesting.stage3d.starling
{
	import com.greensock.easing.Strong;
	import com.greensock.TweenMax;
	import flash.events.AccelerometerEvent;
	import flash.geom.Point;
	import flash.sensors.Accelerometer;
	import starling.display.Quad;
	import starling.display.Sprite;
	import starling.events.Event;
	import starling.events.Touch;
	import starling.events.TouchEvent;
	import starling.events.TouchPhase;
	
	/**
	 * @author ZoulouX
	 */
	public class FirstStarlingTestRoot extends Sprite
	{
		protected var _quad:Quad;
		protected var _accelerometer:Accelerometer;
		protected var _rotationSpeed:Number				= .2;
		
		protected var _touchX:Number;
		protected var _touchY:Number;
		
		protected var _speedX:Number;
		protected var _speedY:Number;
		
		public function FirstStarlingTestRoot ()
		{
			addEventListener(Event.ADDED_TO_STAGE, init);
			addEventListener(Event.ENTER_FRAME, enterFrameHandler);
			addEventListener(TouchEvent.TOUCH, touchEventHandler);
			
			_accelerometer = new Accelerometer();
			//_accelerometer.setRequestedUpdateInterval(0);
			//_accelerometer.addEventListener(AccelerometerEvent.UPDATE, accelerometerUpadedHandler);
		}
		
		protected function touchEventHandler (event:TouchEvent):void
		{
			var touch:Touch = event.getTouch(stage);
			var location:Point = touch.getLocation(stage);
			
			if (touch.phase == TouchPhase.BEGAN)
			{
				TweenMax.killTweensOf(this);
				
				_touchX = location.x;
				_touchY = location.y;
				
				_speedX = 0;
				_speedY = 0;
			}
			else if (touch.phase == TouchPhase.MOVED)
			{
				_speedX = location.x - _touchX;
				_speedY = location.y - _touchY;
				
				_touchX = location.x;
				_touchY = location.y;
				
				x += _speedX;
				y += _speedY;
			}
			else if (touch.phase == TouchPhase.ENDED)
			{
				TweenMax.to(this, .5, {
					x: x + _speedX * 5,
					y: y + _speedY * 5,
					rotation: Math.random() * Math.PI - Math.PI / 2,
					ease: Strong.easeOut
				});
				
				_speedX = 0;
				_speedY = 0;
			}
		}
		
		protected function accelerometerUpadedHandler (event:AccelerometerEvent):void 
		{
			//_rotationSpeed = event.accelerationX;
		}
		
		protected function enterFrameHandler (event:Event):void
		{
			//rotation -= _rotationSpeed / 10;
		}
		
		protected function init (event:Event):void
		{
			stage.color = 0x333333;
			
			_quad = new Quad(200, 200);
			
			pivotX = 100;
			pivotY = 100;
			
			_quad.setVertexColor(0, 0xFFFFFF);
			_quad.setVertexColor(1, 0xFFFFFF);
			_quad.setVertexColor(2, 0x999999);
			_quad.setVertexColor(3, 0x999999);
			
			x = (stage.stageWidth - _quad.width >> 1) + pivotX;
			y = (stage.stageHeight - _quad.height >> 1) + pivotY;
			
			addChild(_quad);
		}
	}
}